$(document).ready(function(){
	$.ajax({
		url:"/slogans/write/"+$('#writeCopyContainer').attr('ad_id')+".json",
		success:jsonWriteCopyContainer
	});
});

function jsonWriteCopyContainer(data){
	if(data.url){
		$('#writeCopyContainer').load(data.url,loadWriteCopyContainer);
	}else if(data.error){
		if(data.onerror){
			eval(data.onerror);
		}else{
			$('#writeCopyContainer .errorMsg').fadeIn('fast').html(data.error).delay(1500).fadeOut('fast');
		}
	}else if(data.reload){
		if($('#writeCopyContainer #SloganDirect:checked').val()=='1'){
			$.popover({
				url:'/pubs/publish/'+data.slogan_id,
				success:load_publish_cnt,
				offset_parent:$('#writeCopyContainer')
			});
		}else{
			location.reload();
		}
	}
}

function similarSloganExists(sloganId,p){
	$.popover({
		url:'/slogans/similarSloganExists/'+sloganId+'/'+p,
		success:function(){
			$('.popover-cnt').delegate('a.publish-it','click',function(){
				$.popover({
					url:'/pubs/publish/'+sloganId,
					success:load_publish_cnt,
					offset_parent:$('#writeCopyContainer')
				});
				return false;
			});
		},offset_parent:$('#writeCopyContainer')
	});
}


function loadWriteCopyContainer(data){
	$('#writeCopyContainer').hide();
	$('#writeCopyContainer').html(data).fadeIn('fast');
	checkLength();
	$('#writeCopyContainer form').ajaxForm({
		beforeSubmit:function(){
			$('#writeCopyContainer .publish').hide();
			$('#writeCopyContainer .publishLoading').show();
		},
		success:function(data){
			jsonWriteCopyContainer(data);
			$('#writeCopyContainer .publish').show();
			$('#writeCopyContainer .publishLoading').hide();
		}
	});
	$(".writeCopy textarea").live('keyup',function(){
		checkLength();
	});
}

function checkLength(){
	var counter=$(".writeCopy .header .charCounter");
	var copyLen=0;
	if($('.writeCopy #SloganSlogan').val()){
		copyLen=$('.writeCopy #SloganSlogan').val().length;
	}
	var len=counter.attr('max')-copyLen;
	counter.html(len);
	if(len<0){
		counter.attr('style','color:#D40D12;');
		return true;
	}else{
		counter.attr('style','color:#666;');
		return false;
	}
}